// 使用 window 对象来存储状态，防止重复声明
if (typeof window.canvasSelector === 'undefined') {
    window.canvasSelector = {
        isSelecting: false,
        highlightElements: [], // 改为数组存储多个高亮元素
        canvasElements: []    // 存储对应的Canvas元素
    };
}

// 接收来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "startSelect") {
        // 如果已经在选择模式，就不要重复初始化
        if (!window.canvasSelector.isSelecting) {
            window.canvasSelector.isSelecting = true;
            highlightAllCanvases();
            addSelectionListeners();
        }
        // 发送响应表示成功接收
        sendResponse({ success: true });
    }
    // 返回 true 表示会异步发送响应
    return true;
});

// 高亮所有Canvas
function highlightAllCanvases() {
    // 清理之前的高亮元素
    cleanup();

    const canvases = document.getElementsByTagName('canvas');
    if (canvases.length === 0) {
        return;
    }

    Array.from(canvases).forEach(canvas => {
        const highlightElement = document.createElement('div');
        highlightElement.style.position = 'fixed';
        highlightElement.style.border = '2px solid #4CAF50';
        highlightElement.style.backgroundColor = 'rgba(76, 175, 80, 0.1)';
        highlightElement.style.pointerEvents = 'auto'; // 改为可点击
        highlightElement.style.cursor = 'pointer';     // 设置鼠标样式
        highlightElement.style.zIndex = '10000';

        const rect = canvas.getBoundingClientRect();
        highlightElement.style.display = 'block';
        highlightElement.style.left = rect.left + 'px';
        highlightElement.style.top = rect.top + 'px';
        highlightElement.style.width = rect.width + 'px';
        highlightElement.style.height = rect.height + 'px';

        // 为高亮元素添加点击事件
        highlightElement.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            downloadCanvas(canvas);
            cleanup();
        });

        document.body.appendChild(highlightElement);
        window.canvasSelector.highlightElements.push(highlightElement);
        window.canvasSelector.canvasElements.push(canvas);
    });
}

// 添加选择监听器
function addSelectionListeners() {
    // 不再需要全局点击事件
}

// 下载Canvas
function downloadCanvas(canvas) {
    try {
        const dataUrl = canvas.toDataURL('image/png');
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `canvas-${timestamp}.png`;

        const link = document.createElement('a');
        link.download = filename;
        link.href = dataUrl;
        link.click();
    } catch (error) {
        console.error('无法下载Canvas:', error);
        alert('无法下载此Canvas，可能是跨域限制或其他安全策略导致。');
    }
}

// 清理
function cleanup() {
    window.canvasSelector.isSelecting = false;
    // 清理所有高亮元素
    window.canvasSelector.highlightElements.forEach(element => {
        if (element) {
            element.remove();
        }
    });
    window.canvasSelector.highlightElements = [];
    window.canvasSelector.canvasElements = [];
} 